﻿using System;
using System.Text;

namespace BizElements.Core.ProviderComponents
{
    /// <summary>Renders aggregate function as SQL element.</summary>
    sealed class GenericAggregateFunctionRenderer : IAggregateFunctionRenderer
    {
        /// <summary>
        /// Renders aggregate function as SQL element.
        /// </summary>
        /// <param name="aggregateFunction">Aggregate function.</param>
        /// <param name="dbms">Target DBMS.</param>
        /// <param name="output">StringBuilder to which SQL is appended.</param>
        /// <param name="allParameters">SQL parameter collection to which the object's and its children's
        /// parameters are added. After the rendering is done the collection contains all parameters with unique names.</param>
        public void Render(AggregateFunction aggregateFunction, DbmsType dbms, StringBuilder output, DbParameterCollection allParameters)
        {
            output.Append(aggregateFunction.Name);
            output.Append("(");
            if (aggregateFunction.Distinct)
                output.Append("DISTINCT ");

            if (aggregateFunction.FunctionArguments.Count > 0)
            {
                for (int paramIdx = 0; paramIdx < aggregateFunction.FunctionArguments.Count - 1; paramIdx++)
                {
                    aggregateFunction.FunctionArguments[paramIdx].Render(dbms, output, allParameters);
                    output.Append(", ");
                }

                aggregateFunction.FunctionArguments[aggregateFunction.FunctionArguments.Count - 1].Render(dbms, output, allParameters);
            }

            output.Append(")");
        }
    }
}